import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:marquee/marquee.dart';

import 'package:mobile_vpn/common/cpn/show_bottom_sheet.dart';
import 'package:mobile_vpn/pages/home_page/widget/wave_border_paintar.dart';
import 'package:mobile_vpn/pages/login_page/login_page.dart';

import '../../theme/color_palettes.dart';

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  RxDouble percentage = 0.0.obs;
  late AnimationController percentageAnimationController;
  late Animation<double> _animation;
  RxInt selected = 0.obs;
  RxBool isClick = false.obs;
  RxDouble rocketBottom = 0.0.obs;
  RxDouble rocketWidth = 40.0.obs;
  late final AnimationController _controller;
  RxString _marqueeText = ''.obs;
  RxBool isMarqueePaused = false.obs; // 控制跑马灯暂停状态

  @override
  void initState() {
    super.initState();
    _fetchMarqueeText();
    percentageAnimationController =
    AnimationController(vsync: this, duration: Duration(milliseconds: 2000))
      ..repeat()
      ..addListener(() {
        percentage.value = percentageAnimationController.value * pi * 2;
      });

    _controller = AnimationController(
      duration: Duration(seconds: 3),
      vsync: this,
    )..forward();
    _animation = Tween<double>(begin: 0, end: 1).animate(_controller);
  }

  void _fetchMarqueeText() async {
    await Future.delayed(Duration(seconds: 1));
    _marqueeText.value = "【系统公告】VIP用户专享高速通道已开通【系统公告】VIP用户专享高速通道已开通";
  }

  @override
  void dispose() {
    percentageAnimationController.stop();
    percentageAnimationController.dispose();
    super.dispose();
  }

  // 判断文本是否溢出
  bool _isTextOverflow(String text, TextStyle style, double maxWidth) {
    final TextPainter textPainter = TextPainter(
      text: TextSpan(text: text, style: style),
      maxLines: 1,
      textDirection: TextDirection.ltr,
    )..layout();
    return textPainter.width > maxWidth;
  }

  @override
  Widget build(BuildContext context) {
    rocketBottom.value = MediaQuery.of(context).size.height / 2 - 30;
    final screenWidth = MediaQuery.of(context).size.width - 40.w; // 减去左右边距
    final bool needMarquee = _marqueeText.value.isNotEmpty &&
        _isTextOverflow(
          _marqueeText.value,
          TextStyle(fontSize: 20),
          screenWidth,
        );

    return Obx(() {
      return Scaffold(
        backgroundColor: ColorPalettes.instance.background,
        body: CustomScrollView(
          slivers: [
            SliverAppBar(
              title: Text(
                "VPN",
                style: TextStyle(
                  color: ColorPalettes.instance.firstText,
                  fontSize: 36.w,
                  fontWeight: FontWeight.w500,
                ),
              ),
              centerTitle: true,
              backgroundColor: Colors.transparent,
            ),
            SliverToBoxAdapter(
              child: Container(
                margin: EdgeInsets.only(top: 30.h),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                  Container(
                  height: 55,
                  margin: EdgeInsets.symmetric(horizontal: 20.w),
                  child: _marqueeText.value.isEmpty
                      ? SizedBox()
                      : GestureDetector(
                    onTap: () {
                      isMarqueePaused.value = !isMarqueePaused.value;
                    },
                    child: Container(
                      width: screenWidth, // 固定背景宽度
                      decoration: BoxDecoration(
                        color: Colors.black.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      padding: EdgeInsets.symmetric(vertical: 10.h),
                      child: Center( // 使用 Center 小部件来居中对齐
                        child: isMarqueePaused.value || !needMarquee
                            ? Text(
                          _marqueeText.value,
                          style: TextStyle(
                            fontSize: 20,
                            color: ColorPalettes.instance.firstText,

                          ),
                          overflow: TextOverflow.ellipsis, // 添加省略号
                          maxLines: 1, // 限制为一行
                        )
                            : Marquee(
                          key: ValueKey(isMarqueePaused.value), // 使用key重建组件
                          text: _marqueeText.value,
                          style: TextStyle(
                            fontSize: 20,
                            color: ColorPalettes.instance.firstText,
                      
                          ),
                          velocity: 50,
                          blankSpace: 100.0,
                          startPadding: 20.0,
                          fadingEdgeStartFraction: 0.1,
                          fadingEdgeEndFraction: 0.1,
                          pauseAfterRound: needMarquee
                              ? Duration.zero
                              : Duration(minutes: 1),
                        ),
                      ),
                    ),
                  ),
                ),

                    Container(
                      width: 150,
                      height:150,
                      margin: EdgeInsets.only(top: 200.h),
                      child: AnimatedBuilder(
                        animation: percentageAnimationController,
                        builder: (context, child) {
                          return CustomPaint(
                            foregroundPainter: WaveBorderPainter(
                              lineColor: Colors.green,
                              completeColor: ColorPalettes.instance.primary,
                              backgroundColor:selected.value == 0? Colors.green.withOpacity(0.1) :ColorPalettes.instance.primary.withOpacity(0.1), // 设置背景颜色
                              startPercent: percentage.value,
                              isComplete: isClick.value,
                              width: 18.w,
                            ),
                            child: Padding(
                              padding: EdgeInsets.all(28.w),
                              child: Stack(
                                alignment: Alignment.center,
                                children: [
                                  Container(), // 空容器占位，确保背景绘制完整
                                  FadeTransition(
                                    opacity: _animation,
                                    child: Icon(
                                      selected.value == 0
                                          ? Icons.rocket_outlined
                                          : Icons.rocket_launch_outlined,
                                      color: ColorPalettes.instance.primary.withAlpha(255),
                                      size: 80,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          )
                          ;
                        },
                      ),
                    ),
                    SizedBox(height: 35.h),
                    Text(
                      "无线路限制，一键加速全球",
                      style: TextStyle(color: ColorPalettes.instance.firstText),
                    ),
                    SizedBox(height: 35.h),
                    ElevatedButton(
                      style: ButtonStyle(
                        backgroundColor: MaterialStatePropertyAll(
                            ColorPalettes.instance.primary.withAlpha(12)),
                        padding: MaterialStatePropertyAll(
                            EdgeInsets.only(left: 130.w, right: 130.w)),
                      ),
                      onPressed: () {
                        _controller.forward(from: 0.0);
                        if (selected.value == 0) {
                          isClick.value = true;
                          selected.value = 1;
                          percentageAnimationController.forward(from: 0.0);
                        } else {
                          isClick.value = false;
                          selected.value = 0;
                          percentage.value = 0.0;
                          percentageAnimationController.forward(from: 0.0);
                          percentageAnimationController.repeat();
                        }
                      },
                      child: Text(
                        selected.value == 0?  "立即加速":"断开连接",
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          color: ColorPalettes.instance.firstText,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      );
    });
  }

  homeTitleBar() {
    return PreferredSize(
      preferredSize: Size(double.infinity, 88.w),
      child: Container(
        height: 88.w,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              padding: EdgeInsets.only(left: 10.w),
              alignment: Alignment.centerLeft,
              child: GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  showDefaultMediaBottomSheet(context, LoginPage());
                },
                child: Badge(
                  label: Text('开通VIP'),
                  backgroundColor: Color(0xfff4f428),
                  child: CircleAvatar(
                    backgroundImage: AssetImage("ic_default_avatar.webp"),
                  ),
                ),
              ),
            ),
            Expanded(
              child: Center(
                child: Text(
                  "VPN",
                  style: TextStyle(
                    color: ColorPalettes.instance.firstText,
                    fontSize: 36.w,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ),
            SizedBox(width: 32.w),
          ],
        ),
      ),
    );
  }
}

